package com.cloud.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.bean.user.User;
import com.cloud.common.BaseReturn;
import com.cloud.common.JwtUtils;
import com.cloud.controller.admin.from.UserFrom;
import com.cloud.mapper.user.UserMapper;
import com.cloud.service.user.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuyuan
 * @since 2022-11-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public BaseReturn login(UserFrom userFrom) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("user_name",userFrom.getUserName());
        queryMap.put("password",userFrom.getPassword());
        List<User> users = userMapper.selectByMap(queryMap);
        if(users.size() == 1){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            User user = users.get(0);
            String token = JwtUtils.geneJsonWebToken(user.getId(), user.getUserName(), "ADMIN");
            session.setAttribute(token,user.getId());
            return BaseReturn.build("2000","登录成功",token);
        }else if(users.size() == 0){
            return BaseReturn.build("5000","账号或者密码错误");
        }else{
            return BaseReturn.build("5000","账号异常请联系管理员");
        }
    }
}
